package org.lee.export.impl;

import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.lee.export.IPptExporter;
import org.lee.export.model.PptVersion;
import org.lee.export.utils.FileUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jackielee
 * @version 1.0
 * @description PptExporter 2003
 * @date 2021/5/6
 **/
public class PptExporter extends BasicPptExporter implements IPptExporter {

    @Override
    public PptVersion getVersion() {
        return PptVersion.PPT;
    }

    @Override
    protected List<String> doExport(File file, String pathSave) {
        List<String> pngFiles = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file)) {
            HSLFSlideShow ppt = new HSLFSlideShow(fis);
            Dimension pgsize = ppt.getPageSize();
            int idx = 1;
            for (HSLFSlide slide : ppt.getSlides()) {
                for (HSLFShape shape : slide.getShapes()) {
                    if (shape instanceof HSLFTextShape) {
                        HSLFTextShape textShape = (HSLFTextShape) shape;
                        for (HSLFTextParagraph p : textShape) {
                            for (HSLFTextRun r : p) {
                                r.setFontFamily("微软雅黑"); // 防止中文乱码
                            }
                        }
                    }
                }
                String fileName = pathSave + File.separator + FileUtils.getFileName(file) + idx + ".png";
                File pngFile = new File(fileName);
                if (pngFile.exists()) {
                    pngFile.delete();
                }
                System.out.println("exporting the ppt to png, page=" + idx);
                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = img.createGraphics();
                // clear drawing
                g.setPaint(Color.white);
                g.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

                // render
                slide.draw(g);

                g.dispose();
                // save
                try (FileOutputStream fos = new FileOutputStream(pngFile)) {
                    ImageIO.write(img, "png", fos);
                    System.out.println("finish the ppt " + idx + " to png.");
                    pngFiles.add(fileName);
                    ++idx;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OfficeXmlFileException e) {
            e.printStackTrace(); // 2003,2007 ppt
        }
        return pngFiles;
    }
}
